import axios from 'axios';
import { MessageBox, Message } from 'element-ui';
import { stringify } from 'qs';
import router from '../router';
import store from '@store';
import { getToken } from '@/utils/auth';

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: 'http://47.97.114.37:8082',
  timeout: 5000, // request timeout
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
  },
})

// request interceptor
service.interceptors.request.use(
  config => {
    const contentType = 'application/x-www-form-urlencoded; charset=utf-8';
    const methods = ['post', 'put', 'delete'];
    if (config.headers['Content-Type'] === contentType && methods.includes(config.method)) {
      config.data = stringify(config.data);
    }
    if(localStorage.getItem('token')) {
      config.headers['token'] = localStorage.getItem('token');
    }
    // if (store.getters.token) {
    //   config.headers['token'] = getToken()
    // }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
function getQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return '';
}
// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    let recommendPhone = localStorage.getItem('inviteCode');
    if (res.status == 0 || res.status == 1) {
      if (res.status == 1) {
        localStorage.removeItem('token')
        localStorage.clear();
        let path = '/login';
        if (recommendPhone) {
          path = `${path}?inviteCode=${recommendPhone}`
        }
        let data = {
          path: path
        }
        router.push(data);
      }
      return res;
    } else {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
